package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.uitool.ShareBoard;
import com.xn.app.muying.uitool.ShareBoardlistener;
import com.xn.app.muying.uitool.SnsPlatform;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.Share;
import com.xn.app.muying.util.ToastUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;

/**
 * 健康宣教详情页面
 * Created by gaoge on 2016/11/8.
 */

public class EducationDetailsActivity extends BaseActivity {

    //详情ID
    private String detailsID = "";
    //标题
    private String name = "";
    //显示数据的webview
    private WebView webview = null;
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //分享按钮
    private ImageView img_right = null;
    //加载框
    AlertDialog dialog;
    //接受内容
    private Intent intent = null;
    //需要分享的内容标题
    private String shareTitle = "";
    //需要分享的内容简介
    private String shareContent = "";
    //需要分享的内容图片
    private String sharePic = "";
    //记录当前页面的url
    private String newURl="";
    //判断是否可分享
    private int type = -1;   //0 不可分享    1可分享
    //判断页面是否加载完成
    private boolean lean=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_education_details);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，给相应组件添加点击事件
     */
    private void initialization() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "文章查看");
        } catch (Exception e) {
            e.printStackTrace();
        }
        webview = (WebView) findViewById(R.id.webview);
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        //获取数据
        intent = getIntent();
        detailsID = intent.getStringExtra("id");
        name = intent.getStringExtra("name");
        title_name.setText(name);
        type = intent.getIntExtra("type", -1);
        if (type == 1) {
            img_right = (ImageView) findViewById(R.id.img_right);
            img_right.setImageResource(R.mipmap.share);
            img_right.setVisibility(View.VISIBLE);
            shareTitle = intent.getStringExtra("title");
            if (shareTitle.equals("1")) {
                shareTitle = name;
                name = "banner";
            }
            shareContent = intent.getStringExtra("content");
            //qq分享字数不能大于40字
            if (shareContent.length() > 37) {
                shareContent = shareContent.substring(0, 36) + "...";
            }
            sharePic = intent.getStringExtra("pic");
            //分享
            img_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //分享
                    new Share(EducationDetailsActivity.this, shareTitle, shareContent, sharePic, detailsID, name,newURl).startShare();
                }
            });
        }
        //返回键单击事件
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ( webview.canGoBack()) {
                    webview.goBack();// 返回前一个页面
                }else{
                    webview.onResume();
                    finish();
                }
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub

                if (url.contains("alipays://platformapi")){
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return false;
                }else if(url.contains("weidianbuyer")){
                    return false;
                }else{
                    newURl=url;
                    view.loadUrl(url);
                    //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                    return true;
                }
            }

            //页面开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if(!lean){
                    dialog =new MyAlertDialog().ShowDialogWeb(EducationDetailsActivity.this, R.layout.dialog_loading);
                    dialog.setCancelable(true);
                    lean=true;
                }
            }

            //加载结束 （其实页面404等等错误的情况也算加载完成）
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (lean&&dialog != null) {
                    dialog.dismiss();
                    lean=false;
                }
                if(webview.getVisibility()==View.GONE){
                    webview.setVisibility(WebView.VISIBLE);
                }
            }
        });

        //用来获取当前页面标题
        webview.setWebChromeClient(new WebChromeClient(){
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //如果是其他页面，则更改为相应标题
                if(newURl!=null&&!newURl.equals("")&&!newURl.equals("null")){
                    shareTitle=title;
                    title_name.setText(title);
                }
            }

            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if(newProgress==100){
                }
                else{

                }

            }
        });
    }

    /**
     * 功能实现
     */
    private void realize() {

        //获取数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            //webview设置
            WebSettings mWebSettings = webview.getSettings();
            mWebSettings.setJavaScriptEnabled(true);
            mWebSettings.setLoadWithOverviewMode(true);
            mWebSettings.setUseWideViewPort(true);
            mWebSettings.setDefaultTextEncodingName("GBK");
            mWebSettings.setLoadsImagesAutomatically(true);
            //加载内容
            webview.loadUrl(APIMethod.EducationDetails(detailsID));
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 点击返回键
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 关闭页面
     */
    @Override
    protected void onDestroy() {
        try {
            ViewGroup view = (ViewGroup) getWindow().getDecorView();
            view.removeAllViews();
        }catch(Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
    }
}
